<template>
  <div class="rowVipPrice">
    <el-button type="primary" @click="editVIPPrice(index,vipJson)">会员价格</el-button>
    <!-- 商品列表 -->
    <goods-sku-v-i-p-price
      ref="goodsSkuVipPrice"
      :visible="visible"
      :index="index"
      @handelClose="handelClose"
      @handelLevelList="handelLevelList"
    />
  </div>
</template>

<script>
import GoodsSkuVIPPrice from '@/components/GoodsSkuVIPPrice'
import { vipLevelList } from '@/api/customAPI/shop/vipManage'
export default {
  components: { GoodsSkuVIPPrice },
  props: {
    index: { type: Number, required: true },
    vipJson: { type: String, default: null }
  },
  data() {
    return {
      visible: false,
      levelList: []
    }
  },
  methods: {
    handelClose() {
      this.visible = false
    },
    editVIPPrice(index, vipJson) {
      this.visible = true
      vipLevelList({
        page: 1,
        limit: 0
      }).then(res => {
        const data = res.data.data.data
        const json = JSON.parse(vipJson)
        if (this.levelList.length == 0) {
          if (!json || json.length == 0) {
            data.forEach(item => {
              this.levelList.push({
                id: item.id,
                vipLevelName: item.vipLevelName,
                vipName: item.vipName,
                number: 0,
                price: 0
              })
            })
          } else if (json.length > 0) {
            data.forEach(item => {
              this.levelList.push({
                id: item.id,
                vipLevelName: item.vipLevelName,
                vipName: item.vipName,
                number: 0,
                price: 0
              })
            })
            json.forEach(inf => {
              this.levelList.forEach(info => {
                if (info.id == inf.id) {
                  info.number = inf.number
                  info.price = inf.price
                }
              })
            })
          }
        }
        this.$refs.goodsSkuVipPrice.setLevelList(this.levelList)
      })
    },
    handelLevelList(list) {
      if (list.length > 0) {
        const json = []
        for (let i = 0; i < list.length; i++) {
          if (list[i].number != 0 && list[i].price == 0) {
            this.$message.error(list[i].vipLevelName + '价格与数量不可同时为0')
            return
          } else if (list[i].price != 0 && list[i].number == 0) {
            this.$message.error(list[i].vipLevelName + '价格与数量不可同时为0')
            return
          } else {
            json.push({
              id: list[i].id,
              level: parseInt(list[i].vipLevelName.replace('vip', '')),
              number: list[i].number,
              price: list[i].price
            })
          }
        }
        if (json.length > 0) {
          this.$emit('submitVip', JSON.stringify(json), this.index)
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
